var UserCreate = function() {

    var initPickers = function() {

        jQuery.validator.addMethod("regex", function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
                "Giá trị không hợp lệ"
                );

        //init date pickers
        $('.date-picker').datepicker({
            rtl: Metronic.isRTL(),
            language: 'vi',
            autoclose: true
        });

        // general settings
        $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
                '<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
                '<div class="progress progress-striped active">' +
                '<div class="progress-bar" style="width: 100%;"></div>' +
                '</div>' +
                '</div>';
        $.fn.modalmanager.defaults.resize = true;
    }

    var handleValidation_Profile = function() {

        var form = $('#form-profile');
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);

        form.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                username: {
                    minlength: 10,
                    required: true
                },
                birthday: {
                    regex: /(\d{2})-(\d{2})-(\d{4})/,
                    required: true
                },
                baptism_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                eucharist_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                confirmation_date: {
                    regex: /[0-9][0-9]-[0-1][0-9]-[1-2][0-9][0-9][0-9]/
                },
                email: {
                    email: true
                },
                password: {
                    minlength: 6,
                    regex: /(?=.*\d)(?=.*[a-zA-Z]).{6,}/,
                    required: true
                },
                retype_password: {
                    minlength: 6,
                    required: true,
                    equalTo: "#password"
                }
            },
            messages: {
                username: {
                    minlength: 'Tối thiểu 10 ký tự',
                    required: 'Bắt buộc nhập'
                },
                birthday: {
                    required: 'Bắt buộc nhập'
                },
                email: {
                    email: 'Email không hợp lệ'
                },
                password: {
                    minlength: 'Tối thiểu 6 ký tự',
                    required: 'Bắt buộc nhập',
                    regex: "Mật Khẩu phải chứa ký tự số <strong>0-9</strong> và chữ cái <strong>a-Z</strong>"
                },
                retype_password: {
                    minlength: 'Tối thiểu 6 ký tự',
                    required: 'Bắt buộc nhập',
                    equalTo: "Chưa khớp với Mât Khẩu Mới"
                }
            },
            invalidHandler: function(event, validator) { //display error alert on form submit 
                success.hide();
                error.show();
                Metronic.scrollTo(error, -200);
            },
            errorPlacement: function(error, element) { // render error placement for each input type
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },
            highlight: function(element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group 
            },
            unhighlight: function(element) { // revert the change done by hightlight

            },
            success: function(label, element) {
                var icon = $(element).parent('.input-icon').children('i');
                $(element).closest('.form-group').removeClass('has-error'); // set success class to the control group
                icon.removeClass("fa-warning");
            },
            submitHandler: function(form) {
                success.show();
                error.hide();

                form.submit();
            }
        });
    }

    var handleValidation_File = function() {

        var form = $('#form-file');
        var error = $('.alert-danger', form);
        var success = $('.alert-success', form);

        form.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                usertype: {
                    required: true
                }
            },
            invalidHandler: function(event, validator) { //display error alert on form submit 
                success.hide();
                error.show();
                Metronic.scrollTo(error, -200);
            },
            errorPlacement: function(error, element) { // render error placement for each input type

                if (element.attr("name") == 'file') {
                    error.insertAfter($(".fileinput", form));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },
            highlight: function(element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group 
            },
            unhighlight: function(element) { // revert the change done by hightlight

            },
            success: function(label, element) {
                var icon = $(element).parent('.input-icon').children('i');
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                icon.removeClass("fa-warning").addClass("fa-check");
            },
            submitHandler: function(form) {
                success.show();
                error.hide();
            }
        });

        $(':file').fileupload({
            dataType: 'json',
            submit: function(e, data) {
                if (form.valid()) {
                    $(this).fileupload('send', data);
                }
                return false;
            },
            beforeSend: function(e, data) {
                error.hide();
                success.hide();
            },
            done: function(e, response) {

                if (response.result.code == 200) {
                    handleOrders(response.result.cacheID);
                    $('div.row-table').show();
                    form.hide();
                } else {
                    error.show();
                }
            },
            fail: function(e, response) {
                error.show();
            }
        });
    }

    var handleOrders = function($cacheID) {

        var table = $("#datatable_list");
        var grid = new Datatable();

        grid.init({
            src: table,
            onSuccess: function(grid) {
                // execute some code after table records loaded
            },
            onError: function(grid) {
                // execute some code on network or other general error 
            },
            dataTable: {// here you can define a typical datatable settings from http://datatables.net/usage/options 
                'sAjaxSource': table.attr('action') + "/" + $cacheID,
                "aoColumns": [
                    {
                        "mDataProp": "checkbox",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "actions",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "saint",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "username",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "birthday",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "gender",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "class",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "phone",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "address",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "parish",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "baptism_date",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "eucharist_date",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "confirmation_date",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "father_saint",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "father_name",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "mother_saint",
                        "sClass": "no-wrap"
                    },
                    {
                        "mDataProp": "mother_name",
                        "sClass": "no-wrap"
                    }
                ],
                "bSort": false,
                "bServerSide": true
            }
        });

        // handle filter
        grid.getDataTable().on('change', '.form-filter[name^="filter_"]', function(e) {
            $('.filter-submit', grid.getDataTable()).trigger('click');
        });

        grid.getTableWrapper().on('change', '.table-group-action-input', function(e) {
            if ($(this).val() == 'setclass') {
                $(this).parent().find('.setclass').show();
            }
            else {
                $(this).parent().find('.setclass').hide();
            }
        });

        // handle group actionsubmit button click
        grid.getTableWrapper().on('click', '.table-group-action-submit', function(e) {
            e.preventDefault();
            var action = $(".table-group-action-input", grid.getTableWrapper());
            if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
                grid.addAjaxParam("sAction", "group_action");
                grid.addAjaxParam("sGroupActionName", action.val());
                var records = grid.getSelectedRows();
                for (var i in records) {
                    grid.addAjaxParam(records[i]["name"], records[i]["value"]);
                }

                if (action.val() == 'setclass') {
                    grid.addAjaxParam('class_id', $('.setclass', grid.getTableWrapper()).val());
                }

                grid.getDataTable().fnStandingRedraw();
                grid.removeAjaxParam('sAction');
                grid.removeAjaxParam('sGroupActionName');
                grid.removeAjaxParam('class_id');
                for (var i in records) {
                    grid.removeAjaxParam(records[i]["name"]);
                }
            } else if (action.val() == "") {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: $('input:hidden.error-no-action').val(),
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            } else if (grid.getSelectedRowsCount() === 0) {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: $('input:hidden.error-no-item').val(),
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            }
        });

        var $modal = $('#ajax-modal');

        table.on("click", "button.btn-edit", function() {
            // create the backdrop and wait for next modal to be triggered
            $('body').modalmanager('loading');

            $modal.load($(this).attr('data-href'), '', function() {
                $modal.modal();
            }).on('hidden', function() {
                grid.getDataTable().fnStandingRedraw();
            });
        });
    }

    return {
        //main function to initiate the module
        init: function() {

            initPickers();
            handleValidation_Profile();
            handleValidation_File();
        }
    };

}();